/* Copyright (c) 2008-2010 -- CommonsWare, LLC
 * Modified by Aris Priyantoro

	 Licensed under the Apache License, Version 2.0 (the "License");
	 you may not use this file except in compliance with the License.
	 You may obtain a copy of the License at

		 http://www.apache.org/licenses/LICENSE-2.0

	 Unless required by applicable law or agreed to in writing, software
	 distributed under the License is distributed on an "AS IS" BASIS,
	 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	 See the License for the specific language governing permissions and
	 limitations under the License.
 */

package com.pituruh.tjroute;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import com.pituruh.utils.ShelterXMLHandler;
import com.pituruh.utils.ShelterSitesList;
import com.pituruh.views.BaloonLayout;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

public class ChooseShelter extends MapActivity implements Runnable {
	private MapView map = null;
	private MyLocationOverlay me = null;
	private BaloonLayout noteBaloon;
	/** Create Object For SiteList Class */
	ShelterSitesList sitesList = null;
	private String selectedShelter;
	/*private ProgressDialog pd;*/
	ProgressBar pb;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map_choose_shelter);
		
		 Bundle extras = getIntent().getExtras();
	     selectedShelter = extras.getString("selectedShelter");

		map = (MapView) findViewById(R.id.map);
		Resources res = getResources();
		int colors[] = { res.getColor(R.color.actionbar_color_1),
				res.getColor(R.color.actionbar_color_2) };
		GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,
				colors);
		LinearLayout layout = (LinearLayout) findViewById(R.id.buttonlayout);
		layout.setBackgroundDrawable(grad);

		TextView title_bar = (TextView) findViewById(R.id.title_bar);
		title_bar.setText(R.string.choose_shelter);

		map.getController().setZoom(17);
		map.setBuiltInZoomControls(true);
		me = new MyLocationOverlay(this, map);
		map.getOverlays().add(me);

        /****progress dialog***/
		/*		pd = ProgressDialog.show(this, getString(R.string.working), getString(R.string.loading_data_from_server), true,
		false);
*/		pb = (ProgressBar) findViewById(R.id.title_progress);
		pb.setVisibility(View.VISIBLE);
		
		Thread thread = new Thread(this);
		thread.start();

		/****end of progress dialog***/		
	}
	
	public void run() {
		try {

			/** Handling XML */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();

			/** Send URL to parse XML Tags */
			URL sourceUrl = new URL("http://transjogja.only.web.id/app/xml/shelter.xml");

			/** Create handler to handle XML Tags ( extends DefaultHandler ) */
			ShelterXMLHandler myXMLHandler = new ShelterXMLHandler();
			xr.setContentHandler(myXMLHandler);
			xr.parse(new InputSource(sourceUrl.openStream()));

		} catch (Exception e) {
			System.out.println("XML Pasing Excpetion = " + e);
		}

		/** Get result from MyXMLHandler SitlesList Object */
		sitesList = ShelterXMLHandler.sitesList;

		handler.sendEmptyMessage(0);
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			/*pd.dismiss();*/
			pb.setVisibility(View.GONE);
			
			if (sitesList == null) {
				Toast.makeText(getApplicationContext(), R.string.failed_loading, Toast.LENGTH_SHORT)
							.show();
				finish();
			}
			else {
				setupOverlay();
			}
		}
	};
	
	private void setupOverlay(){
		Drawable marker = getResources().getDrawable(R.drawable.marker);

		marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker
				.getIntrinsicHeight());

		map.getOverlays().add(new SitesOverlay(marker));

		CreateBaloon();	
	}
	
	@Override
	public void onStart() {
		super.onStart();
/*		try {

			*//** Handling XML *//*
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();

			*//** Send URL to parse XML Tags *//*
			URL sourceUrl = new URL("http://transjogja.only.web.id/app/xml/shelter.xml");

			*//** Create handler to handle XML Tags ( extends DefaultHandler ) *//*
			ShelterXMLHandler myXMLHandler = new ShelterXMLHandler();
			xr.setContentHandler(myXMLHandler);
			xr.parse(new InputSource(sourceUrl.openStream()));

		} catch (Exception e) {
			System.out.println("XML Pasing Excpetion = " + e);
		}

		*//** Get result from MyXMLHandler SitlesList Object *//*
		sitesList = ShelterXMLHandler.sitesList;

		Drawable marker = getResources().getDrawable(R.drawable.marker);

		marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker
				.getIntrinsicHeight());

		map.getOverlays().add(new SitesOverlay(marker));

		me = new MyLocationOverlay(this, map);
		map.getOverlays().add(me);

		CreateBaloon();		*/
	}

	@Override
	public void onResume() {
		super.onResume();

		me.enableCompass();
	}

	@Override
	public void onPause() {
		super.onPause();

		me.disableCompass();
	}

	@Override
	protected boolean isRouteDisplayed() {
		return (false);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_S) {
			map.setSatellite(!map.isSatellite());
			return (true);
		} else if (keyCode == KeyEvent.KEYCODE_Z) {
			map.displayZoomControls(true);
			return (true);
		}

		return (super.onKeyDown(keyCode, event));
	}

	public void CreateBaloon() {
		LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		noteBaloon = (BaloonLayout) layoutInflater.inflate(R.layout.infobaloon,
				null);
		
		ImageButton btn_close = (ImageButton) noteBaloon.findViewById(R.id.btn_close);
		btn_close.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				map.removeView(noteBaloon);
				noteBaloon.setVisibility(View.GONE);
			}
		});
				

		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

		layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
		layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
		noteBaloon.setLayoutParams(layoutParams);
	}

	private GeoPoint getPoint(double lat, double lon) {
		return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
	}
	
	public void onSaveClick(View v) {
		 Intent intent = new Intent();
         
         Bundle extras = new Bundle();
         extras.putString("selectedShelter", selectedShelter);
         intent.putExtras(extras);
         setResult(RESULT_OK, intent);        
         finish();//Finish  current activity
	}

	private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
		private List<OverlayItem> items = new ArrayList<OverlayItem>();
		private Drawable marker = null;
		private int indexOverlay = 0;

		public SitesOverlay(Drawable marker) {
			super(marker);
			this.marker = marker;

			for (int i = 0; i < sitesList.getName().size(); i++) {
				items.add(new OverlayItem(getPoint(sitesList.getLatitude().get(i),
						sitesList.getLongitude().get(i)), sitesList.getName().get(i), 
						"Desc: " + sitesList.getName().get(i)));
				if (sitesList.getName().get(i).equals(selectedShelter))
					indexOverlay = i;
			}

			((TextView) findViewById(R.id.shelter)).setText(selectedShelter);
			MapController mc = map.getController();
			mc.animateTo(getPoint(sitesList.getLatitude().get(indexOverlay),
					sitesList.getLongitude().get(indexOverlay)));
			map.invalidate();

			populate();
		}

		@Override
		protected OverlayItem createItem(int i) {
			return (items.get(i));
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			super.draw(canvas, mapView, shadow);

			boundCenterBottom(marker);
		}

		@Override
		public int size() {
			return (items.size());
		}

		@Override
		public boolean onTouchEvent(MotionEvent event, MapView mapView) {
			final int action = event.getAction();
			final int x = (int) event.getX();
			final int y = (int) event.getY();
			boolean result = false;

			if (action == MotionEvent.ACTION_DOWN) {
				for (OverlayItem item : items) {
					Point p = new Point(0, 0);

					map.getProjection().toPixels(item.getPoint(), p);

					if (hitTest(item, marker, x - p.x, y - p.y)) {
						map.removeView(noteBaloon);
						noteBaloon.setVisibility(View.VISIBLE);

						GeoPoint pt = map.getProjection().fromPixels(p.x,
								p.y - 20);
						
						((TextView) noteBaloon.findViewById(R.id.note_label))
								.setText(item.getTitle());
						TextView text = ((TextView) noteBaloon
								.findViewById(R.id.note_text));
						text.setMovementMethod(new ScrollingMovementMethod());
						text
								.setText("Latitude: " + pt.getLatitudeE6() + " Longitude: " + pt.getLongitudeE6());

						map.getController().animateTo(pt);
						map.addView(noteBaloon, new MapView.LayoutParams(200,
								100, pt, MapView.LayoutParams.BOTTOM_CENTER));

						selectedShelter = item.getTitle();
						((TextView) findViewById(R.id.shelter)).setText(item.getTitle());
						break;
					}
				}

			}

			return (result || super.onTouchEvent(event, mapView));
		}
	}

}